package com.seekting.mynews;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;

import com.seekting.mynews.manager.Manager;
import com.seekting.mynews.manager.NewsManager;
import com.seekting.mynews.manager.VolleyRequestManager;
import com.seekting.util.SLog;

import java.util.LinkedHashMap;

public class App extends Application {
    private VolleyRequestManager volleyRequestManager;
    private Manager newsManager;
    private static App app;
    private String processName;
    private LinkedHashMap<Class<? extends Manager>, Manager> managers;

    public String getProcessName() {
        return processName;
    }

    @Override
    public void onCreate() {
        app = this;
        super.onCreate();
        processName = getCurProcessName(this);

        initManagers();

    }

    private static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    public static App getApp() {
        return app;
    }

    private void initManagers() {
        managers = new LinkedHashMap<Class<? extends Manager>, Manager>();
        volleyRequestManager = new VolleyRequestManager(this);
        newsManager = new NewsManager(volleyRequestManager.getRequestQueue(), this);
        managers.put(VolleyRequestManager.class, volleyRequestManager);
        managers.put(NewsManager.class, newsManager);
    }

    public <T extends Manager> T getManager(Class<T> t) {
        Object o = managers.get(t);
        SLog.d(o);
        return t.cast(managers.get(t));
    }
}
